package com.ruiysoft.service.order.facade;

import com.alibaba.fastjson.JSON;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruiysoft.entity.order.OrderMain;
import com.ruiysoft.entity.order.OrderPay;
import com.ruiysoft.entity.order.OrderPayTransaction;
import com.ruiysoft.entity.sys.SysMicroShop;
import com.ruiysoft.pub.core.ResultCode;
import com.ruiysoft.service.order.IOrderMQAfterOperate;
import com.ruiysoft.service.order.IOrderMainService;
import com.ruiysoft.service.order.IOrderPayService;
import com.ruiysoft.service.order.anno.OrderOperate;
import com.ruiysoft.service.order.bean.OrderPaymentCallbackDto;
import com.ruiysoft.service.order.consts.OperatorIdEnum;
import com.ruiysoft.service.order.consts.OrderDBStatusEnum;
import com.ruiysoft.service.order.consts.OrderOperateTypeEnum;
import com.ruiysoft.service.order.consts.OrderPayStatusEnum;
import com.ruiysoft.service.sys.ISysMicroShopService;
import com.ruiysoft.sms.service.SmsService;
import com.ruiysoft.util.NumberConst;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.Optional;

/**
 * Date : 2018/11/24
 *
 * @author WenJialu
 */
@Component
public class OrderPaymentCallbackFacade {

	private static Logger logger = LoggerFactory.getLogger(OrderPaymentCallbackFacade.class);

	@Resource
	IOrderMainService orderMainService;
	@Resource
	IOrderPayService orderPayService;
	@Resource
	OrderPubFacade orderPubFacade;
	@Resource
	IOrderMQAfterOperate orderMQAfterOperate;
    @Resource
    ISysMicroShopService shopService;

    @Resource
    SmsService smsService;
	/**
	 * 支付回调
	 *
	 * @param dto
	 */
	@Transactional(rollbackFor = Exception.class)
	@OrderOperate(orderNo = "#dto.orderNo", operateType = OrderOperateTypeEnum.CUSTOMER_PAID, operatorId = OperatorIdEnum.SYSTEM_AUTO_OPERATE)
	public OrderPaymentCallbackDto paymentCallback(OrderPaymentCallbackDto dto) {
		if(logger.isDebugEnabled()){
			logger.debug("OrderPaymentCallback,入参:", JSON.toJSONString(dto));
		}

		boolean result = false;
		if (null == dto) {
			//TODO 何时会传入空？

		} else {
			//查询订单号
			OrderPayTransaction pt = orderPubFacade.getOrderPayTransaction(dto.getSysTransactionNo());
			dto.setOrderNo(pt.getOrderNo());
			OrderMain om = orderPubFacade.getOrderMain(dto.getOrderNo());

            SysMicroShop shop = shopService.getById(om.getShopId());
            logger.info("店铺ID:---------"+shop.getId());
			smsService.sendPlaceAnOrder(shop.getTelephone(),om.getOrderNo());

			//主表 && 支付表
			result = paymentCallbackOrderMain(dto) && paymentCallbackOrderPay(dto);
			//mq
//			if (dto.isSuccess()) {
//				OrderMain orderMain = orderPubFacade.getOrderMain(pt.getOrderNo());
//				orderMQAfterOperate.sendAfterPaid(pt.getOrderNo(), pt.getPayAmount(), orderMain.getFreight(), pt.getCreateTime(), DateUtils.addDays(pt.getCreateTime(), 7), orderMain.getShopId(), orderMain.getUserId(), orderMain.getOpenId());
//			}
			System.out.println("支付回调,开始计算佣金=================================result, " + result);
            logger.info("支付回调,开始计算佣金=================================");
			if(result){//如果成功,则计算分销提成
				System.out.println("支付回调,开始计算佣金");
                logger.info("支付回调,开始计算佣金");
                try {
					shopService.calculationWxg(om);
				}catch (Exception e){
					logger.info("计算佣金失败"+e.getMessage());
				}
			}
		}

		dto.setResultCode(result?ResultCode.CODE_SUCCESS:ResultCode.CODE_COMMON_ERROR);

		return dto;
	}

	private boolean paymentCallbackOrderMain(OrderPaymentCallbackDto dto) {
		OrderMain record = new OrderMain();
		QueryWrapper<OrderMain> ew = new QueryWrapper<>();
		record.setStatus(OrderDBStatusEnum.SHOP_CONFIRMED_WATTING_FOR_DELIVER.getCode())
				.setTransactionNo(dto.getTransactionId())
				.setCollectedAmount(Optional.ofNullable(dto.getPayAmount()).map(BigDecimal::longValue).orElse(NumberConst.ZERO_LONG))
				.setPayTime(new Date());

		ew.eq("order_no", dto.getOrderNo())
				.eq("status", OrderDBStatusEnum.CUSTOMER_CONFIRMED_WAITING_FOR_PAYMENT.getCode())
				.eq("del_flag", false);
		return orderMainService.update(record, ew);
	}

	private boolean paymentCallbackOrderPay(OrderPaymentCallbackDto dto) {
		OrderPay record = new OrderPay();

		record.setTransactionNo(dto.getTransactionId())
				.setAmount(Optional.ofNullable(dto.getPayAmount()).map(BigDecimal::longValue).orElse(NumberConst.ZERO_LONG))
				.setStatus(dto.isSuccess() ? OrderPayStatusEnum.PAY_SUCCESS.getCode() : OrderPayStatusEnum.PAY_FAILED.getCode())
				.setPayTime(new Date())
				.setUpdateTime(new Date())
				.setMessage(dto.getErrorMessage());

		return orderPayService.update(record
				, new QueryWrapper<OrderPay>()
						.eq("order_no", dto.getOrderNo())
						.in("status", Arrays.asList(OrderPayStatusEnum.WAITING_FOR_PAY.getCode(), OrderPayStatusEnum.PAY_FAILED.getCode())));
	}

}
